<template>
    <div v-if="!success">
        <h1>注册账号</h1>
        <el-page-header content="注册页面"></el-page-header>
        <div class="center">
            <el-form
                ref="user"
                :model="userdata"
                label-width="90px"
                :rules="rules"
                class="demo-ruleForm"
                status-icon
                >
                <el-form-item label="用户名" prop="user">
                    <el-input v-model="userdata.user" placeholder="请输入用户名" autocomplete="off" minlength="3" maxlength="10" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="密码"  prop="password1">
                    <el-input  v-model="userdata.password1" type="password" placeholder="请输入密码" autocomplete="off" minlength="3" maxlength="8" show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码"  prop="password2">
                    <el-input  v-model="userdata.password2" type="password" placeholder="请输入密码" autocomplete="off" minlength="3" maxlength="8" show-password></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input  v-model="userdata.phone" placeholder="请输入手机号" autocomplete="off"  maxlength="11" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop='imageCode'>
                    <!-- 图片验证码 -->
                    <el-input 
                    placeholder="验证码" 
                    v-model="userdata.imageCode"
                    :style="{width:'52%'}"
                    maxlength="4"
                    show-word-limit
                    ></el-input>
                    <img class='imageCode' v-bind:src="iamgeCodeUrl" alt="图形验证码" @click="genImageCode">
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="register('user')">注册账号</el-button>
                    <!-- <el-button @click="reset('user')">重置</el-button> -->
                </el-form-item>
            </el-form>
        </div>
    </div>
    <!-- 注册成功返回登录界面 -->
    <!-- <div class="bottom" v-if="success">
        <el-result icon="success" title="注册成功!" subTitle="点击返回登录页面">
            <template v-slot:extra>
                <el-button type="primary" @click="login()">返回登录</el-button>
            </template>
        </el-result>
    </div> -->
</template>

<script>
import {v4 as uuid4} from 'uuid'
import { get, post } from "../../utils/request";
export default {
    name:"Login",
    data(){
        // 效验用户名是否符合规则重复
        var username = (rule, value, callback) => {
            // 匹配汉字汉字、字母、数字
            let reg = /^[\u4E00-\u9fa5\w]{3,10}$/g
            if (reg.test(value)) {
                get("users/check/username/" + value + "/").then((resp) => {
                    console.log(resp)
                    if(resp.data.code == 200){
                        callback();
                    }else{
                        callback(new Error(resp.data.msg));
                    }
                }).catch((err) => {
                    callback(new Error('该用户名已存在！'));
                });
            }else{
                callback(new Error('用户名长度3-10之间,允许汉字、字母、数字！'));
            }
        };
        // 判断密码、密钥类型
        var clas = (rule, value, callback) => {
            let reg = /^\w{3,8}$/
            if (reg.test(value)) {
                callback();
            }else{
                callback(new Error('密码只能由字母、数字组成'));
            }
        };
        // 判断密码一致
        var pwd = (rule, value, callback) => {
            if (value == this.userdata.password1) {
                callback();
            } else {
                callback(new Error('两次输入的密码不一致！'));
            }
        };
        // 判断手机号
        var phones = (rule, value, callback) => {
            let reg = /^\d{11}$/
            if (reg.test(value)) {
                callback();
            }else{
                callback(new Error('手机号由11位数字组成'));
            }
        };
        // 校验图片验证码
        var validateImageCode = (rule, value, callback) => {
            if (value === "") {
                return callback(new Error("请输入图片验证码"));
            }
            // 图片验证码是由字母、数字组成，长度为4
            const iamgeCodeRule = /^[a-zA-Z0-9]{4}$/;
            if (iamgeCodeRule.test(value)) {
                get("/users/check_image_code/", {
                    params:{
                        imageCodeID: this.imageCodeID,
                        imageCode: this.userdata.imageCode,
                    }
                })
                .then(res => {
                    if(res.data.code == 200){
                        return callback();
                    }else{
                        return callback(new Error(res.data.msg))
                    }
                }).catch(err => {
                    return Promise.reject(err)
                    })
            } else {
                return callback(new Error("图片验证码不正确！"));
            }
        }
        return{
            imageCodeID: "",//即生成的uuid
            iamgeCodeUrl: "", //图形验证码的地址
            userdata:{
                user:"",
                password1:"",
                password2:"",
                phone:"",
                imageCode:"",
            },
            
            flag: false, 
            user_flag : false,
            rules: {
                user: [
                    { required: true, message: '用户名不能为空', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
                    { validator: username, trigger: 'blur' }
                ],
                password1: [
                    { required: true, message: '密码不能为空', trigger: 'blur' },
                    { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
                    { validator: clas, trigger: 'blur' },
                ],
                password2: [
                    { required: true, message: '确认密码不能为空', trigger: 'blur' },
                    { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' },
                    { validator: clas, trigger: 'blur' },
                    { validator: pwd, trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                    { max: 11, message: '手机号长度为 11 个字符', trigger: 'blur' },
                    { validator: phones, trigger: 'blur' },
                ],
                imageCode: [
                    { required: true, message: '未填写验证码！', trigger: 'blur' },
                    { min: 4, max: 4, message: '验证码长度为4个字符', trigger: 'blur' },
                    { validator: validateImageCode, trigger: 'blur' },
                ],
            },
            success:false
        }
    },
    mounted(){
        this.genImageCode()
    },
    methods:{
        // 生成图片验证码地址
        genImageCode(){
            // 生成一个uuid
            this.imageCodeID = uuid4(),     //npm install -- save uuid
            // 生成一个图片验证码地址
            this.iamgeCodeUrl = "/users/image_code/" + this.imageCodeID + "/"
        },

        reset(formName){
            this.$refs[formName].resetFields();
        },
        register(formName){
            // 已勾选，则不显示提示信息
            this.flag = false
            this.$refs["user"].validate((valid) => {
                console.log(valid)
                if (valid) {
                    post("/users/register/",{
                        username:this.userdata.user,
                        password:this.userdata.password1,
                        mobile:this.userdata.phone,
                    }
                    ).then((resp) => {
                        if(resp.data.code == 200){
                            this.success = true
                            this.$message({message:'注册成功！',type:"success",showClose:true,});
                        }else{
                            this.$message({message:resp.data.msg,type:"error",showClose:true,});
                        }
                    }).catch((err) => {
                        this.$message({message:'注册失败！',type:"error",showClose:true,});
                    });
                } else {
                    this.$message({message:'注册信息未填写完毕！',type:"warning",showClose:true,});
                    return false;
                }
            });
        },
        login(){
            if(this.success == true){
                this.$router.push({name:"Login",params:{user:this.userdata.user,password:this.userdata.password1}})
            }else{
                this.$router.push("/login")
            }
        }
    }
}
</script>

<style>



</style>